﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;

using SmallERP.MODEL.FoundationModel;
using SmallERP.MODEL.PrintManage;
using SmallERP.Bll.PrintManage;
using SmallERP.COM;
using System.Security.Cryptography;
using SmallERP.Bll.Com;
using System.Runtime.InteropServices;
using SmallERP.Bll.MakeBigPic;
using System.ServiceModel;
using Smallerp.Contracts;


namespace SmallERP.PrintManage
{
    public partial class FrmMain : Form
    {
        #region 私有成员

        private Printer_info _printer = null; //打印机
        private PaperInfoModel _paper = null;   //打印纸
        private double _preRemainLength;//打印纸剩余长度(单位：厘米)
        private string _hotDirPath = string.Empty;//热文件夹
        private string _monitorDirPath = string.Empty;//监控文件夹
        private bool _isFileMoving = false; //是否正在移动照片
        private Thread sendPrintThread = null;//发送图片线程

        private SmallERP.Bll.PrintManage.BoardBLL boardBLL = null;
        private PaperBLL paperBLL;
        private bool IsClear = false;

        #endregion

        #region 公共成员

        public delegate void ControlsStatusHander(bool flag);

        [DllImport("kernel32.dll")]
        public static extern int WinExec(string exeName, int operType);

        [DllImport("shell32.dll ")]
        public static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);


        #endregion

        #region 属性

        public double PreRemainLength
        {
            set { _preRemainLength = value; }
            get { return _preRemainLength; }
        }
        public bool IsFileMoving
        {
            get { return _isFileMoving; }
            set { _isFileMoving = value; }
        }
        public Printer_info Printer
        {
            get { return _printer; }
            set { _printer = value; }

        }

        public PaperInfoModel Paper
        {
            get { return _paper; }
            set { _paper = value; }
        }

        #endregion



        public FrmMain()
        {
            InitializeComponent();
            _proxyOperateDB = new ChannelFactory<IOperateDB>("IOperateDB");
            _OperateDb = _proxyOperateDB.CreateChannel();
            boardBLL = new SmallERP.Bll.PrintManage.BoardBLL(_OperateDb);
            paperBLL = new PaperBLL(_OperateDb);
        }
        ChannelFactory<IOperateDB> _proxyOperateDB; //创建代理
        IOperateDB _OperateDb;
        private void FrmMain_Load(object sender, EventArgs e)
        {
            //初始化控件
            InitControlsStatus();
            //选择打印机
            try
            {
                SelectPrinter();
            }
            catch (EndpointNotFoundException ex)
            {
                MessageBox.Show("无法连接到:" + DataTransfer.IPadress);
                Environment.Exit(1);
            }
            catch (Exception exx)
            {
                MessageBox.Show("网络错误：" + exx.Message);
                Environment.Exit(1);
            }
            //访问共享 
            //CheckPrinterFolder();
            //获得打印纸
            GetUsingPaper(_printer.PrinterID);
            //绑定大板
            LinkGridControlBoard();
            //设置状态栏
            SetPrintManageStatus();

            //监控文件夹开始
            timer1.Enabled = true;
            IsClear = _OperateDb.GetIsClearPhoto();
            IsClear = false;

        }

        private void CheckPrinterFolder()
        {
            var result = WNetConnectionHelper.WNetAddConnection(_printer.HotFolderUserName, _printer.HotFolderPwd, _printer.HotDirPath.Trim(), null);

            if (result == 0)
            {
               
            }
            else
            {
                MessageBox.Show("打印机"+_printer.PName+"的热文件夹无法访问");
            }
        }

        /// <summary>
        /// 选择打印机
        /// </summary>
        private void SelectPrinter()
        {
            FrmSelectPrinter selectPrinter = new FrmSelectPrinter(_OperateDb);
            selectPrinter.ShowDialog(this);
            if (_printer != null)
            {
                _hotDirPath = _printer.HotDirPath;          //取得打印机热文件夹路径
                _monitorDirPath = _printer.MonitorDirPath;  //取得打印机监控文件夹路径
            }
        }
        /// <summary>
        /// 获得当前打印纸
        /// </summary>
        /// <param name="printerid"></param>
        private void GetUsingPaper(int printerid)
        {
            _paper = paperBLL.GetUsingPaper(printerid);
            if (_paper == null)
            {
                tsbtnPrintControl.Enabled = false;
                tsbtnPaperManage.Enabled = true;
                MessageBox.Show("请添加打印纸", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                _preRemainLength = _paper.LastLength * 100;// 厘米
            }
        }

        private void tsbtnPaperManage_Click(object sender, EventArgs e)
        {
            FrmChangePaper frmChangePaper = new FrmChangePaper(_OperateDb);
            frmChangePaper.PrinterInfo = _printer;
            frmChangePaper.ChangePaperCompleteEvent += new FrmChangePaper.ChangePaperCompleteHander(ChangPaperComplete);
            frmChangePaper.ShowDialog(this);
        }
        /// <summary>
        ///  换纸完成后操作
        /// </summary>
        private void ChangPaperComplete()
        {
            tsbtnPrintControl.Enabled = true;
            _preRemainLength = _paper.LastLength * 100;
            SetPrintManageStatus();
        }
        /// <summary>
        /// 设置状态栏
        /// </summary>
        private void SetPrintManageStatus()
        {
            double noPrintArea = 0;
            double printedArea = 0;
            GetNoPrintArea(ref noPrintArea, ref printedArea);
            tssHaveNotPrint.Text = Math.Round(noPrintArea, 4).ToString() + "平方" + cmbUnit.Text;
            tssHavePrint.Text = Math.Round(printedArea, 4).ToString() + "平方" + cmbUnit.Text;
            if (_paper != null)
            {
                tssPaperID.Text = _paper.PrintPaperId.ToString();
                tssLastLength.Text = Math.Round(_paper.LastLength, 4).ToString() + "米";
                if (_paper.LastLength < 3)
                {
                    tssLastLength.ForeColor = Color.Red;
                }
                tssPaperWidth.Text = _paper.Width+ "英寸";
                tssPaperFace.Text = _paper.PaperFaceName;
                tssPaperType.Text = _paper.PaperTypeName;
            }
            tssPrinter.Text = _printer.PName;
            this.Text = string.Format("输出管理({0}),当前连接IP地址:{1}", _printer.PName,DataTransfer.IPadress);

        }
        private void GetNoPrintArea(ref double noPrintArea, ref double printedArea)
        {

            List<BoardModel> list = (List<BoardModel>)gridControlBoard.DataSource;
            foreach (var item in list)
            {
                if (item.Status == (int)Status.EnumBoardStatus.WaitingPrint)
                {
                    noPrintArea += item.BoardArea;
                }
                if (item.Status == (int)Status.EnumBoardStatus.Printed)
                {
                    printedArea += item.BoardArea;
                }
            }
        }
        /// <summary>
        /// 绑定大板数据
        /// </summary>
        private void LinkGridControlBoard()
        {
            int status = 0;
            switch (cmbStatus.SelectedIndex)
            {

                case 0://今日全部
                    status = -1;
                    break;
                case 1://未打印
                    status = (int)SmallERP.COM.Status.EnumBoardStatus.WaitingPrint;
                    break;
                case 2://正在打印
                    status = (int)SmallERP.COM.Status.EnumBoardStatus.Printing;
                    break;
                case 3://今日打印完成
                    status = (int)SmallERP.COM.Status.EnumBoardStatus.Printed;
                    break;
                case 4://错误
                    status = (int)SmallERP.COM.Status.EnumBoardStatus.Error;
                    break;
                case 5://暂停

                    status = (int)SmallERP.COM.Status.EnumBoardStatus.Pause;
                    break;
                case 6://等待生成大图
                    status = (int)SmallERP.COM.Status.EnumBoardStatus.waitProduct;
                    break;
                default:
                    status = 0;
                    break;

            }
            GetBoardList(status);
        }
        /// <summary>
        /// 获得大板数据
        /// </summary>
        /// <param name="status"></param>
        private void GetBoardList(int status)
        {
            gridControlBoard.DataSource = boardBLL.GetBoardInfoList(status, _printer.PrinterID, cmbUnit.SelectedIndex);
            gridViewBoard.RefreshData();

        }
        /// <summary>
        /// 初始化控件状态
        /// </summary>
        private void InitControlsStatus()
        {
            cmbStatus.SelectedIndex = 0;
            cmbUnit.SelectedIndex = 1;

        }

        private void cmbStatus_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            LinkGridControlBoard();
            //选今日全部数据状态栏的平米统计才准确
            if (cmbStatus.SelectedIndex == 0)
            {
                SetPrintManageStatus();
            }
        }

        private void tsbtnPrintControl_Click(object sender, EventArgs e)
        {
            if (tsbtnPrintControl.Text == "开始打印")
            {

                try
                {
                    if (!Directory.Exists(_hotDirPath + "\\temp-wh"))
                    {
                        Directory.CreateDirectory(_hotDirPath + "\\temp-wh");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("连接热文件夹失败，请检查网络连接！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (sendPrintThread == null)
                {
                    sendPrintThread = new Thread(new ThreadStart(SendPrintControl));
                    sendPrintThread.Name = "SendPrint";
                    sendPrintThread.IsBackground = true;
                    sendPrintThread.Start();
                }
                else
                {
                    try
                    {
                        sendPrintThread.Resume();
                    }
                    catch (ThreadStateException ex)
                    {
                        //线程尚未启动，或是已死
                    }
                }
                SetControlsStatusOnPrinting(true);
            }
            else
            {
                if (!_isFileMoving)
                {
                    if (sendPrintThread != null && sendPrintThread.ThreadState != System.Threading.ThreadState.WaitSleepJoin)
                    {
                        try
                        {
                            sendPrintThread.Suspend();
                            SetControlsStatusOnPrinting(false);
                        }
                        catch (Exception ex)
                        {

                            MessageBox.Show(ex.Message);
                        }

                    }

                }
                else
                {
                    MessageBox.Show("正在移动图片，请稍后再停止", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        /// <summary>
        /// 发送图片控制
        /// </summary>
        private void SendPrintControl()
        {
            bool flag = true;
            while (true)
            {
                Thread.Sleep(3000);
                int count = this.GetFileCount();

                if (count < 2)
                {
                    flag = SendPrint(2 - count);
                }
                if (!flag)//发送图片异常，停止发送
                {
                    if (toolStrip1.InvokeRequired)
                    {
                        ControlsStatusHander controlStatusDelegate = new ControlsStatusHander(SetControlsStatusOnPrinting);
                        Invoke(controlStatusDelegate, new object[] { false });
                    }
                    sendPrintThread.Suspend();
                }
            }
        }
        /// <summary>
        /// 获取监控文件夹图片个数
        /// </summary>
        /// <returns></returns>
        private int GetFileCount()
        {
            try
            {
                string strMidPath = string.Empty;
                if (!string.IsNullOrEmpty(_monitorDirPath))
                {
                    strMidPath = _monitorDirPath;
                }
                else
                {
                    strMidPath = _hotDirPath;
                }

                int moniFileCount = GetDirCount(strMidPath);//查看监控文件夹里有没有图片
                if (moniFileCount < 2)
                {
                    if (GetDirCount(_hotDirPath + "\\temp-wh") >= 1)//如果监控文件夹中只有一张或是没有图片，则查看临时文件夹中是否有图片
                    {
                        return 2;
                    }
                }
                return moniFileCount;
            }
            catch
            {
                return 0;
            }

            //try
            //{
            //    string strMidPath = string.Empty;
            //    if (!string.IsNullOrEmpty(_monitorDirPath))
            //    {
            //        strMidPath = _monitorDirPath;
            //    }
            //    else
            //    {
            //        strMidPath = _hotDirPath;
            //    }
            //    string[] file1s = Directory.GetFiles(strMidPath, "*.jpg");
            //    string[] file2s = Directory.GetFiles(strMidPath, "*.tif");
            //    string[] file3 = Directory.GetFiles(strMidPath, "*.imt");
            //    string[] file4 = Directory.GetFiles(strMidPath, "*.IMT");

            //    return (file1s.Length + file2s.Length+file3.Length+file4.Length);
            //}
            //catch
            //{
            //    return 0;
            //}
        }

        /// <summary>
        /// 得到文件夹中的TIF和JPG的文件的数据
        /// </summary>
        /// <param name="strDirPath"></param>
        public int GetDirCount(string strDirPath)
        {
            string[] file1s = Directory.GetFiles(strDirPath, "*.jpg");
            string[] file2s = Directory.GetFiles(strDirPath, "*.tif");
            string[] files3 = Directory.GetFiles(strDirPath, "*.imt");

            return (file1s.Length + file2s.Length + files3.Length);
        }

        /// <summary>
        /// 发送图片
        /// </summary>
        /// <param name="bigBoardNum"></param>
        /// <returns></returns>
        private bool SendPrint(int bigBoardNum)
        {
            string hotDirPat = _printer.HotDirPath.Trim();//打印机的热文件夹
            bool isNeedUpdatePaper = true;//是否需要换纸标志
            bool islengthEnough = true;//纸长是否足够
            bool iswidthEnough = true;//纸宽是否足够
            double paperWidth = 0.0;//纸宽
            double bordWidth = 0.0;//将要发送的大板的宽度（都是英寸为单位）
            double bordLength = 0.0;

            if (_paper != null)
            {
                paperWidth = _paper.Width*2.54;
            }
            else
            {
                paperWidth = 0;
                return false;
            }



            int boardID = 0;//大板ID
            string picpath = string.Empty;
            string picName = string.Empty;
            string paperTypeName = string.Empty;
            string paperFaceName = string.Empty;
            int length;
            int width;
            int dpi;

            List<BoardModel> boardModelList = boardBLL.GetBoardInfoList((int)Status.EnumBoardStatus.WaitingPrint, _printer.PrinterID, cmbUnit.SelectedIndex);
            if (boardModelList.Count > 0)
            {
                try
                {
                    int CurSendBigBoard = 0;

                    for (int i = 0; i < boardModelList.Count; i++)
                    {
                        boardID = boardModelList[i].BoardId;
                        picpath = boardModelList[i].PicPath;
                        picName = picpath.Substring(picpath.LastIndexOf("\\") + 1);
                        paperFaceName = boardModelList[i].PaperFaceName;
                        paperTypeName = boardModelList[i].PaperTypeName;
                        length = boardModelList[i].Length;//相素
                        width = boardModelList[i].Height;
                        dpi = boardModelList[i].DPI;
                        bordLength = Math.Round(length / (double)dpi * 2.54, 2);
                        bordWidth = Math.Round(width / (double)dpi * 2.54, 2);

                        if (_preRemainLength < bordLength)
                        {
                            islengthEnough = false;
                            continue;
                        }
                        if (((paperWidth - 0.254) > bordWidth) || (bordWidth > paperWidth + 0.254))
                        {
                            iswidthEnough = false;
                            continue;
                        }
                        try
                        {
                            if ((((paperWidth - 0.254) > bordWidth) || (bordWidth > paperWidth + 0.245)) || PreRemainLength < bordLength || (paperFaceName != _paper.PaperFaceName && paperFaceName != "任意") || (paperTypeName != _paper.PaperTypeName && paperTypeName != "任意"))
                            {
                                isNeedUpdatePaper = true;
                                continue;
                            }
                            else
                            {
                                isNeedUpdatePaper = false;
                                _isFileMoving = true;
                                try
                                {
                                    if (!Directory.Exists(hotDirPat + "\\temp-wh\\"))
                                    {
                                        Directory.CreateDirectory(hotDirPat + "\\temp-wh\\");
                                    }

                                    File.Copy(picpath, hotDirPat + "\\temp-wh\\" + picName, true);
                                }
                                catch (Exception ex)
                                {
                                    WriteLogForCheck.WriteLogFile(DateTime.Now.ToString() + " 复制图片异常 " + ex.Message);
                                    _isFileMoving = false;
                                    if (File.Exists(hotDirPat + "\\temp-wh\\" + picName))
                                    {
                                        try
                                        {
                                            File.Delete(hotDirPat + "\\temp-wh\\" + picName);
                                        }
                                        catch (Exception)
                                        {

                                            //throw;
                                        }

                                    }
                                    continue;
                                }

                                //string firstMD5 = GetFileHash(picpath);
                                //string secondMD5 = GetFileHash(hotDirPat + "\\temp-wh\\" + picName);
                                string firstMD5 = "1";
                                string secondMD5 = "1";


                                if (firstMD5 == secondMD5)
                                {
                                    try
                                    {
                                        if (!Directory.Exists(hotDirPat + "\\outPut\\"))
                                        {
                                            Directory.CreateDirectory(hotDirPat + "\\outPut\\");
                                        }
                                        //if (bllMain.SendPrint(boardID) > 0)//如果更新数据库成功后才开始打印
                                        boardModelList[i].Status = (int)SmallERP.COM.Status.EnumBoardStatus.Printing;
                                        if (boardBLL.Update(boardModelList[i]) == 0)//如果更新数据库成功后才开始打印
                                        {
                                            File.Move(hotDirPat + "\\temp-wh\\" + picName, hotDirPat + "\\outPut\\" + picName);
                                        }
                                        else
                                        {
                                            try
                                            {
                                                File.Delete(hotDirPat + "\\temp-wh\\" + picName);
                                            }
                                            catch (Exception)
                                            {

                                                //throw;
                                            }
                                            continue;//如果没有更新成功，则删除图片被试其它的图片
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        WriteLogForCheck.WriteLogFile(DateTime.Now.ToString() + " 剪切图片异常 " + ex.Message);
                                        continue;
                                        //throw;
                                    }
                                    finally
                                    {
                                        _isFileMoving = false;
                                    }
                                    _preRemainLength -= bordLength;

                                }
                                else//如果二张片不相符就先删除TEMP里的照片后再拷一下
                                {
                                    if (File.Exists(hotDirPat + "\\temp-wh\\" + picName))
                                    {
                                        try
                                        {
                                            File.Delete(hotDirPat + "\\temp-wh\\" + picName);
                                        }
                                        catch (Exception)
                                        {

                                            //throw;
                                        }

                                    }
                                    _isFileMoving = false;
                                    continue;
                                }

                                CurSendBigBoard++;
                                if (CurSendBigBoard >= bigBoardNum)//如果已经发送完成就退出
                                {
                                    break;
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            if (e is FileNotFoundException || e is DirectoryNotFoundException)
                            {
                                //DALMain.UpdateBoardErrorStatus(boardID);
                                boardModelList[i].Status = (int)Status.EnumBoardStatus.Error;
                                boardBLL.Update(boardModelList[i]);
                            }
                            else
                            {
                                StringBuilder sb = new StringBuilder();
                                sb.Append(DateTime.Now.ToString());
                                sb.Append("  发送");
                                sb.Append(boardID.ToString());
                                sb.Append("号大板");
                                sb.Append(e.Message);
                                WriteLogForCheck.WriteLogFile(sb);
                            }
                            _isFileMoving = false;
                            continue;
                        }
                    }
                    if (isNeedUpdatePaper)
                    {
                        if (!islengthEnough)
                        {
                            MessageBox.Show("打印纸剩余长度不够，请换纸！\r\n当前剩余长度为：" + PreRemainLength.ToString() + "厘米,纸型：" + paperTypeName + ",纸面：" + paperFaceName, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                        else if (!iswidthEnough)
                        {

                            MessageBox.Show("大板宽度和打印纸不匹配，请换纸！\r\n当前打印纸宽度为：" + paperWidth/2.54+ "英寸,大板宽度：" + bordWidth / 2.54 + "英寸", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                        else
                        {
                            MessageBox.Show("打印纸与大板纸面，纸型不匹配，大板纸型：" + paperTypeName + ",大板纸面：" + paperFaceName, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                    }
                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;

                }
            }
            return true;
        }

        private string GetFileHash(string filePath)
        {
            FileStream fs = new FileStream(filePath, FileMode.Open);
            int len = (int)fs.Length;
            byte[] data = new byte[len];
            fs.Read(data, 0, len);
            fs.Close();
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(data);
            string sResult = "";
            foreach (byte b in result)
            {
                sResult += Convert.ToString(b, 16);
            }
            return sResult;
        }
        /// <summary>
        /// 打印开始或停止时控件状态设置
        /// </summary>
        /// <param name="flag"></param>
        private void SetControlsStatusOnPrinting(bool flag)
        {
            if (flag)
            {
                tsbtnPaperManage.Enabled = false;
                tsbtnPrintControl.Image = global::SmallERP.PrintManage.Properties.Resources.Stop32;
                tslbPrinterStatus.Image = global::SmallERP.PrintManage.Properties.Resources.Green;
                tsbtnPrintControl.Text = "停止打印";
            }
            else
            {
                tsbtnPaperManage.Enabled = true;
                tsbtnPrintControl.Image = global::SmallERP.PrintManage.Properties.Resources.GroupPlay;
                tslbPrinterStatus.Image = global::SmallERP.PrintManage.Properties.Resources.Red;
                tsbtnPrintControl.Text = "开始打印";
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            HandlePrinting();
            LinkGridControlBoard();
            //RefreshPaperStatus();
            //this.FillDataTable();
            //this.SetDataGrid();
        }
        /// <summary>
        /// 定时检查正在打印的大板是否已经被打印完成
        /// </summary>
        private void HandlePrinting()
        {
            DataTable dt = new DataTable();
            string picpath = string.Empty;
            string picName = string.Empty;
            int boardID = 0;
            int length;
            int width;
            int dpi;
            double boardLength;
            double boardWidth;
            try
            {

                string[] files;
                try
                {
                    files = Directory.GetFiles(_monitorDirPath);
                }
                catch (Exception)
                {
                    return;
                    //无效的监控文件夹
                }

                List<BoardModel> boardInfoList = boardBLL.GetBoardInfoList((int)Status.EnumBoardStatus.Printing, _printer.PrinterID, cmbUnit.SelectedIndex);
                for (int i = 0; i < boardInfoList.Count; i++)
                {
                    bool isPrinting=false;//该大板是否正在打印
                    picpath = string.Empty;
                    boardID = boardInfoList[i].BoardId;
                    picpath = boardInfoList[i].PicPath;
                    picName = picpath.Substring(picpath.LastIndexOf("\\") + 1);
                    length = boardInfoList[i].Length;
                    width = boardInfoList[i].Height;
                    dpi = boardInfoList[i].DPI;

                    //bordLength = Math.Round(length / (double)dpi * 2.54, 2);
                    double wasteRate = boardInfoList[i].WasteRate;
                    foreach (var strPicPath in files)
                    {
                        if (strPicPath.Contains(picName.Substring(0, picName.IndexOf("."))))//如果有，则表示该大板正在打印
                        {
                            isPrinting = true;
                            break;
                        }                        
                    }

                    if (isPrinting)
                    {
                        continue;
                    }

                    boardLength = length / dpi * 2.54; //大板长（厘米）
                    boardWidth = width / dpi * 2.54; //大板宽（厘米）
                    //if (!File.Exists(_monitorDirPath + "\\" + picName))
                    //{

                    boardInfoList[i].PrintPaperId = _paper.PrintPaperId;
                    boardInfoList[i].Status = (int)Status.EnumBoardStatus.Printed;
                    boardInfoList[i].PrintNum += 1;
                    boardInfoList[i].LastPrintTime = UnityMethod.GetSystemTime();
                    boardBLL.Update(boardInfoList[i]);

                    _paper = paperBLL.GetUsingPaper(_printer.PrinterID);
                    _paper.LastPrintTime = UnityMethod.GetSystemTime();
                    _paper.LastLength -= boardLength / 100;
                    _paper.LastBordId = boardInfoList[i].BoardId;
                    _paper.PaperConsumptionLength += boardLength / 100;
                    _paper.ValidationArea += boardWidth * boardLength / 10000;//出片面积
                    _paper.InvalidationArea += boardWidth * boardLength / 10000 * wasteRate;//浪费面积
                    int ret = paperBLL.Update(_paper);
                    if (ret == -1)
                    {
                        WriteLogForCheck.WriteLogFile("打印完成后更新打印纸剩余长度失败   " + DateTime.Now.ToString());
                    }
                    //}


                }
            }
            catch (Exception ex)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(DateTime.Now.ToString());
                sb.Append("  打印");
                sb.Append(boardID.ToString());
                sb.Append("号大板 ");
                sb.Append(ex.Message);
                WriteLogForCheck.WriteLogFile(sb);
                return;
            }
        }

        private void tsbtnRefresh_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            try
            {
                HandlePrinting();
                LinkGridControlBoard();
                SetPrintManageStatus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                Cursor = Cursors.Default;
            }

        }

        /// <summary>
        /// 暂停大板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbtnPause_Click(object sender, EventArgs e)
        {
            IDataAccess iDataAccess = new SmallERP.Bll.PrintManage.BoardBLL(_OperateDb);
            int[] rowHandles = gridViewBoard.GetSelectedRows();
            for (int i = 0; i < rowHandles.Length; i++)
            {
                BoardModel boardInfo = (BoardModel)gridViewBoard.GetRow(rowHandles[i]);
                //只暂停未打印的大板
                if (boardInfo.Status == (int)Status.EnumBoardStatus.WaitingPrint)
                {
                    boardInfo.Status = (int)Status.EnumBoardStatus.Pause;
                    iDataAccess.Update(boardInfo);
                }
            }
            LinkGridControlBoard();
        }

        /// <summary>
        /// 恢复大板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbtnResume_Click(object sender, EventArgs e)
        {
            IDataAccess iDataAccess = new SmallERP.Bll.PrintManage.BoardBLL(_OperateDb);
            int[] rowHandles = gridViewBoard.GetSelectedRows();
            for (int i = 0; i < rowHandles.Length; i++)
            {
                BoardModel boardInfo = (BoardModel)gridViewBoard.GetRow(rowHandles[i]);
                //只暂停未打印的大板
                if (boardInfo.Status == (int)Status.EnumBoardStatus.Pause)
                {
                    boardInfo.Status = (int)Status.EnumBoardStatus.WaitingPrint;
                    iDataAccess.Update(boardInfo);
                }
            }
            LinkGridControlBoard();
        }

        /// <summary>
        /// 退版
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbtnBackBoard_Click(object sender, EventArgs e)
        {
            SmallERP.Bll.PrintManage.BoardBLL boardBLL = new SmallERP.Bll.PrintManage.BoardBLL(_OperateDb);
            BoardModel boardInfo = (BoardModel)gridViewBoard.GetFocusedRow();
            if (boardInfo != null)
            {
                if ( boardInfo.Status == (int)Status.EnumBoardStatus.Error || boardInfo.Status == (int)Status.EnumBoardStatus.waitProduct)
                {
                    if (MessageBox.Show("确定要退版吗,?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        try
                        {
                            int ret = boardBLL.DeleteBoard(boardInfo);
                            if (ret < 0)
                            {
                                MessageBox.Show("退版出错，请检查数据库连接", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);

                            }
                            else
                            {
                                LinkGridControlBoard();
                            }
                        }
                        catch (Exception ex)
                        {
                            if (ex is IndexOutOfRangeException)
                            {
                                MessageBox.Show("超时请重新选择", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                                return;
                            }
                        }
                    }
                }else
                {
                    if (IsClear && boardInfo.Status == (int)Status.EnumBoardStatus.WaitingPrint)
                    {
                        MessageBox.Show("照片已经转移不能退版", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                        return;

                    }
                    else if (!IsClear && boardInfo.Status == (int)Status.EnumBoardStatus.WaitingPrint)
                    {
                        if (MessageBox.Show("确定要退版吗,?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            try
                            {
                                int ret = boardBLL.DeleteBoard(boardInfo);
                                if (ret < 0)
                                {
                                    MessageBox.Show("退版出错，请检查数据库连接", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);

                                }
                                else
                                {
                                    LinkGridControlBoard();
                                }
                            }
                            catch (Exception ex)
                            {
                                if (ex is IndexOutOfRangeException)
                                {
                                    MessageBox.Show("超时请重新选择", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                                    return;
                                }
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show(boardInfo.StatusName+"不能退版", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                        return;
                    }

                }
            }
        }

        /// <summary>
        /// 加急
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbtnPriority_Click(object sender, EventArgs e)
        {

            SmallERP.Bll.PrintManage.BoardBLL boardBLL = new SmallERP.Bll.PrintManage.BoardBLL(_OperateDb);
            int[] rowHandles = gridViewBoard.GetSelectedRows();

            FrmPriority frmPriority = new FrmPriority();
            if (frmPriority.ShowDialog() == DialogResult.OK)
            {
                for (int i = 0; i < rowHandles.Length; i++)
                {
                    BoardModel boardInfo = (BoardModel)gridViewBoard.GetRow(rowHandles[i]);
                    if (boardInfo.Status == (int)Status.EnumBoardStatus.WaitingPrint)
                    {
                        try
                        {
                            if (this.CheckStatus(boardInfo, "加急"))
                            {
                                boardInfo.PrintPriority = frmPriority.Priority;
                                boardBLL.Update(boardInfo);
                                LinkGridControlBoard();
                            }
                        }
                        catch (Exception ex)
                        {
                            if (ex is IndexOutOfRangeException)
                            {
                                MessageBox.Show("超时请重新选择", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                                return;
                            }
                            return;
                        }
                    }
                    else
                    {
                        MessageBox.Show("只有“未打印”状态的大板才能加急", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
        }

        private bool CheckStatus(BoardModel boardInfo, string msg)
        {
            if (boardInfo.StatusName != "未打印" && boardInfo.StatusName != "打印完成")
            {
                MessageBox.Show(boardInfo.StatusName + "不能" + msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 重新生成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbtnReProduct_Click(object sender, EventArgs e)
        {
            SmallERP.Bll.PrintManage.BoardBLL boardBLL = new SmallERP.Bll.PrintManage.BoardBLL(_OperateDb);
            BoardModel boardInfo = (BoardModel)gridViewBoard.GetFocusedRow();
            if (boardInfo != null)
            {
                try
                {
                    if (boardInfo.Status == (int)Status.EnumBoardStatus.WaitingPrint || boardInfo.Status == (int)Status.EnumBoardStatus.Error)
                    {
                        if (MessageBox.Show("确定要重新生成该大版吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            boardInfo.Status = (int)Status.EnumBoardStatus.waitProduct;
                            boardBLL.Update(boardInfo);
                            StringBuilder sb = new StringBuilder();
                            sb.Append(DateTime.Now.ToString());
                            sb.Append("  ");
                            sb.Append(boardInfo.BoardId.ToString());
                            sb.Append("号大板重新生成成功");
                            WriteLogForCheck.WriteLogFile(sb);
                            LinkGridControlBoard();
                        }
                    }
                    else
                    {
                        MessageBox.Show(string.Format("{0}不能进行此操作", boardInfo.StatusName), "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    if (ex is IndexOutOfRangeException)
                    {
                        MessageBox.Show("超时请重新选择", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                        return;
                    }

                    return;
                }
            }
        }
        /// <summary>
        /// 重新打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbtnRePrint_Click(object sender, EventArgs e)
        {
            SmallERP.Bll.PrintManage.BoardBLL boardBLL = new SmallERP.Bll.PrintManage.BoardBLL(_OperateDb);
            BoardModel boardInfo = (BoardModel)gridViewBoard.GetFocusedRow();
            if (boardInfo != null)
            {
                if (boardInfo.Status == (int)Status.EnumBoardStatus.Printed)
                {
                    if (MessageBox.Show("确定要重新打印吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        try
                        {
                            boardInfo.Status = (int)Status.EnumBoardStatus.WaitingPrint;

                            //费纸的记录，用于打印出来
                            List<int> RecordIdList = new List<int>();
                            boardBLL.RePrint(boardInfo, out RecordIdList);
                            //FrmShowPaperCode frm = new FrmShowPaperCode();
                            //frm.paperIdList = RecordIdList;
                            //frm.ShowDialog();
                            MessageBox.Show("重新打印完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);

                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                            return;
                        }
                        //StringBuilder sb = new StringBuilder();
                        //sb.Append(DateTime.Now.ToString());
                        //sb.Append("  ");
                        //sb.Append(boardInfo.BoardId.ToString());
                        //sb.Append("号大板重新打印成功");
                        //WriteLogForCheck.WriteLogFile(sb);
                        LinkGridControlBoard();

                    }
                }
                else
                {
                    MessageBox.Show(boardInfo.StatusName + "不能进行此操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                    return;
                }
            }
        }

        private void tsbtnExit_Click(object sender, EventArgs e)
        {
            if (!HaveBoardPrinting())
            {
                if (DialogResult.OK == MessageBox.Show("确认要退出输出管理么？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    Environment.Exit(0);
                }
            }
            else
            {
                MessageBox.Show("要等正在打印的大版打印完成才能退出！", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            }
        }
        private bool HaveBoardPrinting()
        {
            bool flag;
            SmallERP.Bll.PrintManage.BoardBLL boardBLL = new SmallERP.Bll.PrintManage.BoardBLL(_OperateDb);
            List<BoardModel> list = boardBLL.GetBoardInfoList((int)Status.EnumBoardStatus.Printing, _printer.PrinterID, cmbUnit.SelectedIndex);
            if (list.Count > 0)
            {
                flag = true;
            }
            else
            {
                flag = false;
            }
            return flag;

        }

        private void cmbUnit_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            gridColumnBoardArea.Caption = "面积(平方" + cmbUnit.Text + ")";
            gridColumnPaperLength.Caption = "纸长(" + cmbUnit.Text + ")";
            gridColumnPaperWidth.Caption = "纸宽(" + cmbUnit.Text + ")";
            LinkGridControlBoard();
            SetPrintManageStatus();
        }

        private void tsbtnQuery_Click(object sender, EventArgs e)
        {
            FrmQuery._OperateDb = _OperateDb;
            FrmQuery frmQuery = FrmQuery.GetInstance;
            frmQuery.Printer = _printer;
            frmQuery.selectHander = new FrmQuery.SelectHander(SelectResult);
            frmQuery.Show();

        }

        private void SelectResult(int boardid)
        {
            gridControlBoard.DataSource = boardBLL.GetBoardInfoForQuery(boardid, 0, "", cmbUnit.SelectedIndex, _printer.PrinterID);
            gridViewBoard.RefreshData();
        }

        private void tsbtnAddPaperWasteRecord_Click(object sender, EventArgs e)
        {
            FrmAddPaperWasteRecord frm = new FrmAddPaperWasteRecord(_OperateDb);
            frm.PaperInfo = _paper;
            if (DialogResult.OK == frm.ShowDialog())
            {
                _paper = paperBLL.GetUsingPaper(_printer.PrinterID);
                SetPrintManageStatus();
            }

        }

        private void gridViewBoard_DoubleClick(object sender, EventArgs e)
        {
            Board_Info bd = (Board_Info)gridViewBoard.GetFocusedRow();
            if (bd != null)
            {
                FrmBoardDetail frm = new FrmBoardDetail(_OperateDb);
                frm.BoardId = bd.BoardId;
                frm.ShowDialog();
            }

        }

        private void gridViewBoard_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Column.FieldName == "PicPath")
            {
                string fileName = ((Board_Info)gridViewBoard.GetFocusedRow()).PicPath;
                if (fileName.Contains("jpg"))
                {
                    int ret = WinExec(@"explorer /n,/select," + fileName, 1);
                }
            }
        }

        private void gridViewBoard_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            //打开定单目录       
            string infoPath = _printer.HotDirPath;
            ShellExecute(IntPtr.Zero, new StringBuilder("open"), new StringBuilder("explorer.exe"),
                                     new StringBuilder(infoPath), new StringBuilder(string.Empty), 1);
        }
        /// <summary>
        /// 校正纸长
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbtnCalibrationPaperLength_Click(object sender, EventArgs e)
        {
            FrmCalibrationPaperLength frm = new FrmCalibrationPaperLength(_OperateDb);
            frm.Printer = _printer;
            frm.refreshUsingPaperHander = new FrmCalibrationPaperLength.RefreshUsingPaperHander(GetUsingPaper);
            frm.refreshStatusHander = new FrmCalibrationPaperLength.RefreshStatusHander(ChangPaperComplete);
            frm.ShowDialog();
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!HaveBoardPrinting())
            {
                if (!(DialogResult.OK == MessageBox.Show("确认要退出输出管理么？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)))
                {
                    e.Cancel = true;
                }
            }
            else
            {
                e.Cancel = true;
                MessageBox.Show("要等正在打印的大版打印完成才能退出！", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            }
        }

        private void toolStripButtonChangePaperTypeFace_Click(object sender, EventArgs e)
        {
            int[] selectedRows = gridViewBoard.GetSelectedRows();
            List<BoardModel> boardList=new List<BoardModel>();
            foreach (int i in selectedRows)
            {
                BoardModel model = (BoardModel)gridViewBoard.GetRow(i);
                boardList.Add(model);
            }
            FrmChangeTypeFace frmChangeTypeFace = new FrmChangeTypeFace(boardList,_OperateDb);
            if(DialogResult.OK== frmChangeTypeFace.ShowDialog())
            {
                gridControlBoard.RefreshDataSource();
            }

        }

    }
}
